#include "mystdio.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

const char*to_string(int flag)
{
    if(flag & NONE_FLUSH) return "None";
    if(flag & LINE_FLUSH) return "Line";
    if(flag & FULL_FLUSH) return "Full";
    return "nuknow";
}

myfile* myfopen(const char*pathname,const char* mode)
{
    int flag = 0;
    if(strcmp(mode,"r") == 0)
    {
        flag|=O_RDONLY;
    }
    else if(strcmp(mode,"w") == 0)
    {
        flag |= (O_CREAT|O_WRONLY|O_TRUNC);
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag |= (O_CREAT|O_WRONLY|O_APPEND);
    }
    else 
        return NULL;
    
    int fd = 0;
    if(flag & O_WRONLY)
    {
        fd = open(pathname,flag,0666);
    }
    else 
    {
        fd = open(pathname,flag);
    }
    if(fd < 0)
    {
        return NULL;
    }
    
    myfile* fp = (myfile*)malloc(sizeof(myfile)); 
    if(fp == NULL)
    {
        return NULL;
    }
    fp->fileno = fd;
    fp->cap = SIZE;
    fp->pos = 0;
    fp->flush_mode = LINE_FLUSH;
    return fp;
}


void myfflush(myfile* fp)
{
    if(fp->pos == 0) return;
    write(fp->fileno,fp->outbuffer,fp->pos);
    fp->pos = 0;
}


int myfwrite(myfile* fp,const char* s,int len)
{
    memcpy(fp->outbuffer+fp->pos,s,len);
    fp->pos += len;
    if((fp->flush_mode & LINE_FLUSH) && fp->outbuffer[fp->pos-1] == '\n')
    {
        myfflush(fp);
    }
    else if((fp->flush_mode & FULL_FLUSH) && fp->pos == fp->cap)
    {
        myfflush(fp);
    }

}

//int myfread();
void myfclose(myfile* fp)
{
    myfflush(fp);
    close(fp->fileno);
    free(fp);
}



void debugPrintf(myfile* fp)
{
    printf("outbuffer :%s\n",fp->outbuffer);
    printf("fd:%d\n",fp->fileno);
    printf("pos:%d\n",fp->pos);
    printf("cap:%d\n",fp->cap);
    printf("flush_mode:%s\n",to_string(fp->flush_mode));
}





